package team.pwy.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.pwy.mapper.MessageMapper;
import team.pwy.pojo.entity.Message;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public PageInfo<Message> findByStatus(Integer userId,Integer status, Integer pageNum, Integer pageSize) {
        ListOperations lop = redisTemplate.opsForList();
        List messageLists = lop.range("usermessage" + userId, 0, -1);

        if (messageLists != null && !messageLists.isEmpty()) {
            redisTemplate.delete("usermessage" + userId);
        }

        PageHelper.startPage(pageNum, pageSize);
        List<Message> messageList = messageMapper.findByStatus(userId,status);

        if (status == 1 & !messageList.isEmpty()){
            List<Integer> messageIds = new ArrayList<>();
            for (Message message : messageList) {
                messageIds.add(message.getId());
            }
            messageMapper.updateByLook(messageIds);
        }

        return new PageInfo<>(messageList);
    }

    @Override
    public PageInfo<Message> findAllMsg(Integer userId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Message> messageList = messageMapper.findAllMsg(userId);
        return new PageInfo<>(messageList);
    }

    @Override
    public Integer updateByLookReal(Integer userId) {
        return messageMapper.updateByLookReal(userId);
    }
}
